import { addMsgCallBack, removeMsgCallBack, sendCmd } from '@/agora/rtm'
import { toRaw, watch } from 'vue'
import { modelS, SKey } from './store'

const pick = (keys: SKey[]) => {
    const res: Partial<Record<SKey, any>> = {}
    const _s = toRaw(modelS)
    keys.forEach(key => res[key] = _s[key])
    return res
}
watch(modelS, () => {
    const modelConfig = {
        modelGender: modelS.modelGender || 'FEMALE',
        ClothConfig: pick(['ClothIndex']),
        HairConfig: pick(['HairColorIndex', 'HairStyleIndex']),
        FaceConfig: pick(['FaceStyleIndex', 'FaceWide', 'SkinColorIndex', 'JawLength', 'LowJaw']),
        BrowConfig: pick(['BrowStyleIndex']),
        EyeConfig: pick(['EyeBig', 'EyeDistance', 'EyeHeight', 'EyeRotate', 'EyeStyleIndex']),
        NoseConfig: pick(['NoseLength', 'NoseStyleIndex', 'NoseWide']),
        MouthConfig: pick(['MouthBig', 'MouthLip', 'MouthUp'])
    }
    sendCmd('setmodel', modelConfig)
    console.warn(modelConfig)
}, { immediate: true })

// 向左变化量是负的,有是正的
export const rotate = (val: number) => val && sendCmd('handle', { type: val > 0 ? 1 : 0, increment: +Math.abs(val).toFixed(0) })
export const zoom = (val: number) => {
    // val 20-100
    val = +Math.abs(val).toFixed(0)
    // 反向
    const negation = 80 - (val - 20) + 20
    console.log('ppp', { val, negation })
    sendCmd('handle', { type: 3, increment: negation })
}

export const save = async () => {
    let resolve: (msg: string) => void
    const res = new Promise<string>((...args) => [resolve] = args)
    sendCmd('savemodel')
    const callBack = (msg: string) => {
        if (msg.endsWith('.png')) {
            removeMsgCallBack(callBack)
            resolve(msg)
        }
    }
    addMsgCallBack(callBack)
    return res
}
